"use strict";

const Controller = require("egg").Controller;

class CategoryController extends Controller {
  /**
   * 获取分类列表
   */
  async index() {
    const { ctx } = this;
    const { page = 1, pageSize = 20, parentId, name } = ctx.query;

    const categories = await ctx.service.category.getList({
      name,
      parent_id: parentId,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
    });

    ctx.body = {
      code: 0,
      message: "success",
      data: categories,
    };
  }

  /**
   * 获取分类树形结构
   */
  async tree() {
    const { ctx } = this;
    const tree = await ctx.service.category.getTree();

    ctx.body = {
      code: 0,
      message: "success",
      data: tree,
    };
  }

  /**
   * 获取分类详情
   */
  async show() {
    const { ctx } = this;
    const { id } = ctx.params;

    const category = await ctx.service.category.getById(id);

    ctx.body = {
      code: 0,
      message: "success",
      data: category,
    };
  }

  /**
   * 创建分类
   */
  async create() {
    const { ctx } = this;
    const { name, parent_id, icon, sort_order, is_show } = ctx.request.body;

    const category = await ctx.service.category.create({
      name,
      parent_id,
      icon,
      sort_order,
      is_show,
    });

    ctx.body = {
      code: 0,
      message: "创建成功",
      data: category,
    };
  }

  /**
   * 更新分类
   */
  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { name, parent_id, icon, image, sort_order, is_show } =
      ctx.request.body;

    const result = await ctx.service.category.update(id, {
      name,
      parent_id,
      icon,
      image,
      sort_order,
      is_show,
    });

    ctx.body = {
      code: 0,
      message: "更新成功",
      data: result,
    };
  }

  /**
   * 删除分类
   */
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;

    const result = await ctx.service.category.delete(id);

    ctx.body = {
      code: 0,
      message: "删除成功",
      data: result,
    };
  }
}

module.exports = CategoryController;
